<template>
  <el-form
    ref="form"
    :model="form"
    label-width="100px"
    :rules="rules"
  >
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" placeholder="请选择部门负责人">
        <el-option
          v-for="item in employees"
          :key="item.id"
          :label="item.username"
          :value="item.username"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" type="textarea" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateDeptSubmit">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  getEmployeeSimpleAPI,
  addDepartmentAPI,
  getDepartDetailAPI,
  updateDepartmentsAPI
} from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    // 接收父级部门的id
    parentId: {
      type: [Number, String],
      required: true
    },
    // 接收编辑状态
    isEdit: {
      type: Boolean,
      required: true
    },
    // 接收精简后的组织架构信息
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 部门编码校验：部门编码在整个模块中不允许不重复
    const codeVidate = (rules, value, callback) => {
      // 遍历精简后的部门列表，将其部门编码组成新的数组
      let existCodeList = this.originList.map(item => item.code)
      // 如果为编辑状态，则进行判断之前需要将当前部门排除在外
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      // 判断输入的部门编码是否包含在所有部门编码的列表中
      existCodeList.includes(value) ? callback(new Error(`编码${value}已存在`)) : callback()
    }

    // 部门名称校验：部门名称在同级部门中不允许重复
    const nameVidate = (rules, value, callback) => {
      // 筛出同级部门，并将其部门名称组成新的数组
      let existNameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)
      // 判断如果为编辑状态，需要获取当前的部门信息
      if (this.isEdit) {
        const currentDepartment = this.originList.find(item => item.id === this.parentId)
        // 获取当前部门的pid
        const currentPid = currentDepartment.pid
        // 通过当前部门的pid获取其同级部门，并将当前部门排除在外,组成新的部门名称数组(同一级部门的pid相同)
        existNameList = this.originList.filter(item => item.pid === currentPid && item.id !== this.parentId).map(item => item.name)
      }

      // 判断输入的部门名称是否包含在所有部门名称列表中
      existNameList.includes(value) ? callback(new Error(`部门名称${value}已存在`)) : callback()
    }
    return {
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      // 部门负责人列表
      employees: [],
      // 基础校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: nameVidate, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: codeVidate, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getEmployeeSimple()
    this.getDepartDetail()
  },
  methods: {
    // 获取部门负责人
    async getEmployeeSimple() {
      const res = await getEmployeeSimpleAPI()
      console.log(res)
      this.employees = res.data
    },

    // 获取部门详情(编辑数据回填)
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetailAPI(this.parentId)
        console.log(res)
        this.form = res.data
      }
    },

    // 添加部门的方法
    async addDepartments() {
      const res = await addDepartmentAPI({ ...this.form, pid: this.parentId })
      console.log(res)
      // 给出提示
      this.$message.success(res.message)
      // 触发父组件的更新事件
      this.$emit('updateDeptEvent')
    },

    // 编辑部门信息的方法
    async editDepartments() {
      console.log(this.form)
      const res = await updateDepartmentsAPI(this.form)
      console.log(res)
      this.$message(res.message)
      this.$emit('updateDeptEvent')
    },

    // 点击确认，更新组织架构
    updateDeptSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isEdit ? this.editDepartments() : this.addDepartments()
        } else {
          return
        }
      })
    },

    // 点击取消
    cancel() {
      this.$emit('cancelEvent')
    }
  }
}</script>

<style lang="scss" scoped>
form.el-form {
  padding: 0 60px 0 20px;
}
.el-select {
  width: 100%;
}
</style>
